//
//  SEGFaceRecognitionViewController.m
//  SEGStandard
//
//  Created by 乔杨 on 2020/7/6.
//

#import "SEGFaceRecognitionViewController.h"

#if __has_include(<commonThirds/SEGImagePickerManager.h>)
#import <commonThirds/SEGImagePickerManager.h>
#else
#import "SEGImagePickerManager.h"
#endif

#import <SEGViewModel/SEGFaceRecognitionViewModel.h>

@interface SEGFaceRecognitionViewController ()<SEGImagePickerManagerDelegate, UINavigationControllerDelegate>

/** 相机, 相册 */
@property (nonatomic, strong) SEGImagePickerManager *imagePicker;
/// 白色背景
@property (nonatomic, strong) UIView *bgView;
/// title
@property (nonatomic, strong) UILabel *titleLab;
/// 内容
@property (nonatomic, strong) UILabel *contentLab;
/// 人脸识别头像
@property (nonatomic, strong) UIImageView *faceImgView;
/// 规则
@property (nonatomic, strong) UILabel *ruleLab;

/// viewModel
@property (nonatomic, strong) SEGFaceRecognitionViewModel *viewModel;

@end

@implementation SEGFaceRecognitionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showCustomNavigationBackButton];
    
    [self seg_createUI];
    
    // 设置人脸识别图片
    @weakify(self);
    [SVProgressHUD show];
    [self.viewModel.downloadSignal subscribeNext:^(NSString *imagePath) {
        [SVProgressHUD dismiss];
        @strongify(self);
        [self seg_setFaceImageWithImagePath:imagePath];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

#pragma mark - UI
- (void)seg_createUI {
    [self.view addSubview:self.bgView];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(kNavigationBarAndStatusBarHeight);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(84);
    }];
    
    [self.bgView addSubview:self.titleLab];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgView).mas_offset(17.5f);
        make.left.equalTo(self.bgView).mas_offset(15);
    }];
    
    [self.bgView addSubview:self.contentLab];
    [self.contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLab.mas_bottom).mas_offset(10.5f);
        make.left.equalTo(self.bgView).mas_offset(15);
    }];
    
    [self.bgView addSubview:self.faceImgView];
    [self.faceImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bgView);
        make.right.equalTo(self.bgView).mas_offset(-15);
        make.width.height.mas_equalTo(44.f);
    }];
    // 唤起相册
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [self seg_showPhotoLibrary];
    }];
    [self.faceImgView addGestureRecognizer:tap];
    
    self.ruleLab.numberOfLines = 0;
    self.ruleLab.preferredMaxLayoutWidth = LYScreenWidth() - 30;
    [self.view addSubview:self.ruleLab];
    [self.ruleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgView.mas_bottom).mas_offset(15);
        make.left.equalTo(self.view).mas_offset(15);
        make.right.equalTo(self.view).mas_offset(-15);
    }];
}
/// 设置人脸识别图片
/// @param imagePath 图片地址
- (void)seg_setFaceImageWithImagePath:(NSString *)imagePath {
    NSString *imageUrlStr = [NSString stringWithFormat:@"%@%@", kClientImageRootURL, imagePath];
    [self.faceImgView setImageWithURL:[NSURL URLWithString:imageUrlStr] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"face_normal")]];
}
 
#pragma mark - Event
- (void)seg_showPhotoLibrary {
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:@"添加图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alterController addAction:[UIAlertAction actionWithTitle:@"从手机选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePicker = [[SEGImagePickerManager alloc] init];
        self.imagePicker.delegate = self;
        self.imagePicker.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
        self.imagePicker.allowsEditing = YES;
        [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
    }]];
    [alterController addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePicker = [[SEGImagePickerManager alloc] init];
        self.imagePicker.delegate = self;
        self.imagePicker.sourceType = SEGImagePickerManagerSourceTypeCamera;
        self.imagePicker.allowsEditing = YES;
        [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
    }]];
    [alterController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alterController animated:YES completion:nil];
}

#pragma mark - SEGImagePickerManagerDelegate
- (void)seg_imagePickerManager:(SEGImagePickerManager *)manager
        didFinishPickingPhotos:(NSArray<UIImage *> *)photos
                        assets:(NSArray<PHAsset *> *)assets
         isSelectOriginalPhoto:(BOOL)isSelect {
     @weakify(self);
     UIImage *editedImage = [photos lastObject];
    [self.viewModel.uploadIconCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        if (x.boolValue) {
            [SVProgressHUD show];
        } else {
            [SVProgressHUD dismiss];
        }
    }];
    [[self.viewModel.uploadIconCommand execute:editedImage] subscribeNext:^(RACTuple *tuple) {
        RACTupleUnpack(NSString *imagePath, NSString *message) = tuple;
        @strongify(self);
        // 设置人脸识别图片
        [self seg_setFaceImageWithImagePath:imagePath];
        [SEGAlertView showTmepMessageWithMessage:message];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

#pragma mark - Getter
- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        _bgView.backgroundColor = kColor_W;
    }
    return _bgView;
}
- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [[UILabel alloc] init];
        _titleLab.textColor = kColor_1;
        _titleLab.backgroundColor = kColor_W;
        _titleLab.font = kFont_16;
        _titleLab.text = @"采集面部信息";
        _titleLab.layer.masksToBounds = YES;
    }
    return _titleLab;
}
- (UILabel *)contentLab {
    if (!_contentLab) {
        _contentLab = [[UILabel alloc] init];
        _contentLab.textColor = kColor_3;
        _contentLab.backgroundColor = kColor_W;
        _contentLab.font = kFont_13;
        _contentLab.text = @"用于人脸识别开门";
        _contentLab.layer.masksToBounds = YES;
    }
    return _contentLab;
}
- (UIImageView *)faceImgView {
    if (!_faceImgView) {
        _faceImgView = [[UIImageView alloc] init];
        _faceImgView.backgroundColor = kColor_W;
        _faceImgView.contentMode = UIViewContentModeScaleAspectFill;
        _faceImgView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"face_normal")];
        _faceImgView.layer.cornerRadius = 2.f;
        _faceImgView.layer.masksToBounds = YES;
        _faceImgView.userInteractionEnabled = YES;
    }
    return _faceImgView;
}
- (UILabel *)ruleLab {
    if  (!_ruleLab) {
        _ruleLab = [[UILabel alloc] init];
        _ruleLab.textColor = kColor_3;
        _ruleLab.backgroundColor = self.view.backgroundColor;
        _ruleLab.font = kFont_11;
        _ruleLab.text = @"照片要求：1.头部正脸；2.清晰可见；3.无遮挡（避免带墨镜、头发挡住 脸）； 4.无夸张表情；5.不戴口罩；6.无浓妆。";
        _ruleLab.layer.masksToBounds = YES;
    }
    return _ruleLab;
}
- (SEGFaceRecognitionViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGFaceRecognitionViewModel new];
    return _viewModel;
}

@end
